<?php
class Helper_Form{
	private $_form;
	private $_config;
	
	function __construct( $config, $url = '', $methode = 'post' ){
		$this->_config = $config;
		$this->_form = $this->constructForm( $url, $methode );
	}
	
	private function constructForm( $url = '', $methode = 'post' ){
		$data = array(
			'start'=>array( 'html'=>'<form action="'.$url.'" methode="'.$methode.'" >' )
		);
		foreach( $this->_config as $field=>$config ){
			$data[ $field ] = $this->constructField( $field, $config );
		}
		
		$data['end'] = array( 'html'=>'</form>' );
		
		return $data;
	}
	
	private function constructField( $name, $config, $value = "" ){
		if( isset($config['label']) && $config['editable'] !== 'hidden' ) $html = '<label>' . $config['label'] . '</label>';
		elseif( $config['editable'] !== 'hidden' )  $html = '<label>' . $name . '</label>';
		else $html = '';
		
		switch( $config['editable'] ){
			case 'none':{
				$html .= '<span name="' . $name . '">' . $value . '</span>';
				break;
			}
			case 'textarea':{
				$html .= '<textarea name="' . $name . '">' . $value . '</textarea>';
				break;
			}
			case 'select':{
				$html .= '<select name="' . $name . '">'."\n\r";
				foreach( $config['values'] as $val=>$label	 ){
					$selected = ( $val === $value )?' selected="selected"':'';
					$html .= '<option value="' . $val . '"' . $selected . '>' .$label. '</option>'."\n\r";
				}
				$html .= '</select>';
				break;
			}
			default :{
				$html .= '<input name="' . $name . '" type="' . $config['editable'] . '" value="' . $value . '" />';
			}
		}
		$html = '<dd>' . $html . '</dd>';
		return array( 'html'=>$html);
	}
	
	public function getForm(){
		$retour = '';
		foreach( $this->_form as $item  ){
			$retour .= $item['html']."\n\r";
		}
		return $retour;
	}
	
	public function populate( $data ){
		foreach( $data as $k=>$v ){
			if( isset($this->_form[$k]) ){
				$this->_form[$k] = $this->constructField( $k, $this->_config[$k], $v );
			}
		}
	}
}
?>